﻿var jsAppwebPart = jsAppwebPart || {};

jsAppwebPart._hasInit = false;

jsAppwebPart.ensure = function (sourceWebPartId) {

    var isPageEditMode = (document.getElementById('MSOLayout_InDesignMode').value == 1) ? true : false;
    var selectedWpId = document.getElementById('MSOTlPn_SelectedWpId').value;

    var isJsAppWebPart = (selectedWpId == sourceWebPartId) && (isPageEditMode == true) && (jsAppwebPart._hasInit == false);

    if (isJsAppWebPart == true) {
        document.write("<style>.UserGeneric { display: none; }</style>");
        document.write("<style>.ms-TPHeader { display: none; }</style>");

        jQuery(document).ready(function () {

            jsAppwebPart._ensureSections();

            jsAppwebPart._ensureXmlSection();
            jsAppwebPart._ensureXslSection();

            jQuery(".UserGeneric").fadeIn(750);
        });

        jsAppwebPart._hasInit = true;
    }
};

jsAppwebPart._selectedAppServerUrl = "";

jsAppwebPart._headers = null;
jsAppwebPart._bodies = null;

jsAppwebPart._appElements = [];

jsAppwebPart._ensureSections = function () {

    jsAppwebPart._headers = jQuery("#MSOTlPn_Parts .UserGeneric .UserSectionHead");
    jsAppwebPart._bodies = jQuery("#MSOTlPn_Parts .UserGeneric .UserSectionBody");
};

jsAppwebPart._showAppPicker = function () {

    var pickerAppMarkup = "<div id='main-cnt' style='height: 385px;'><div id='search-cnt'>Search:<input type=''/></div><hr style='border: 0px; color: #dedede; height: 2px; background-color: #dedede;'/><div id='app-cnt' style='overflow: auto; overflow-y: visible;overflow-x: hidden; height: 385px;'></div><div style='clear: both'> </div><hr style='border: 0px; color: #dedede; height: 2px; background-color: #dedede;'/><div style='padding: 10px; margin: 5px; text-align: right'><input type='button' id='saveBtn'  value='Save' class='ms-ButtonHeightWidth' /><input id='cancelBtn' type='button' value='Cancel' class='ms-ButtonHeightWidth' /></div></div>";
    var pickerAppMarkupElement = jQuery(pickerAppMarkup)[0];

    var appsContainer = jQuery("#app-cnt", pickerAppMarkupElement);

    var cancelBtnElement = jQuery("#cancelBtn", pickerAppMarkupElement);
    $(cancelBtnElement).click(function () { jsAppwebPart._selectedAppServerUrl = null; SP.UI.ModalDialog.commonModalDialogClose(); });

    var saveBtnElement = jQuery("#saveBtn", pickerAppMarkupElement);
    $(saveBtnElement).click(function () {

        if (jsAppwebPart._selectedAppServerUrl != null) {
            $(jsAppwebPart._xmlInputElement).val(jsAppwebPart._selectedAppServerUrl + "/app.xml");
        }

        var xslLinkValue = $(jsAppwebPart._xslInputElement).val();

        if (!xslLinkValue.length) {

            var siteUrl = _spPageContextInfo.webServerRelativeUrl;
            var xslPath = "/_catalogs/masterpage/JsAppWebPart/sys/app.xsl"

            if (siteUrl != "/")
                xslPath = siteUrl + xslPath;

            $(jsAppwebPart._xslInputElement).val(xslPath);
        }


        jsAppwebPart._selectedAppServerUrl = null;

        SP.UI.ModalDialog.commonModalDialogClose();
    });

    //jQuery().load(tmp, function(result) {

    var options = {
        html: pickerAppMarkupElement,
        title: 'JS apps catalog',
        autoSize: true,
        width: 690,
        height: 500,
        allowMaximize: false
    };

    SP.UI.ModalDialog.showModalDialog(options);
    //
    // load apps

    var siteUrl = _spPageContextInfo.webServerRelativeUrl;

    var clientContext = new SP.ClientContext(siteUrl);
    var appList = clientContext.get_web().get_lists().getByTitle('Master Page Gallery');
    var camlQuery = new SP.CamlQuery();

    camlQuery.set_viewXml("<View Scope='Folder'>" +
                                       "<Query> " +
                                           "<Where>" +
                                               "<Eq>" +
                                                   "<FieldRef Name='FSObjType' />" +
                                                   "<Value Type='Lookup'>1</Value>" +
                                               "</Eq>" +
                                           "</Where>" +
                                       "</Query>" +
                                       "</View>");

    var appFolderPath = "/_catalogs/masterpage/JsAppWebPart/apps";

    if (siteUrl != "/")
        appFolderPath = siteUrl + appFolderPath;

    camlQuery.set_folderServerRelativeUrl(appFolderPath);

    var appItems = appList.getItems(camlQuery);

    clientContext.load(appItems, "Include(EncodedAbsUrl,FileRef,FileLeafRef,Title,Id)");

    clientContext.executeQueryAsync(function () {

        var appItemEnumerator = appItems.getEnumerator();

        jsAppwebPart._appElements = [];

        while (appItemEnumerator.moveNext()) {

            (function (appItem) {

                var appAbsFolder = appItem.get_item('EncodedAbsUrl');
                var fileRef = appItem.get_item('FileRef');
                var title = appItem.get_item('FileLeafRef');

                var metaUrl = appAbsFolder + '/app.description.html';
                var metaImageUrl = appAbsFolder + '/app.icon.png';

                var itemTemplate = "<div data-app-file-ref='" + fileRef + "' style='width:192px;height:96px;float:left;border:1px #91cdf2 solid;padding:10px; margin:5px'>" +
				 					   "<b><span>" + title + "</span></b>" +
				 					   "<hr style='border: 0px; color: #dedede; height: 2px; background-color: #dedede;'/>" +
				 					   "<div style='width: 100%; margin-top: 10px; vertical-align: top'>" +
								 				"<div style='float: left;'>" +
						              	        	"<img class='app-image' style='width: 64px;height: 64px;' />" +
						              	        "</div>" +
						              	        "<div class='app-description' style='float: left; padding-left:5px; width: 120px'> </div>" +
						               "</div>" +
			 					  "</div>";

                var appItemElement = $(itemTemplate)[0];

                $('.app-image', appItemElement).attr("src", metaImageUrl);

                jQuery.get(metaUrl, function (data) {
                    $('.app-description', appItemElement).html(data);
                });

                $(appItemElement).click(function () {
                    jsAppwebPart._selectedAppServerUrl = $(this).attr('data-app-file-ref');

                    $(jsAppwebPart._appElements).each(function () {
                        $(this).css("background-color", "#ffffff");
                    });

                    $(this).css("background-color", "#fdd9d9");
                });

                jsAppwebPart._appElements.push(appItemElement);

                $(appsContainer).append(appItemElement);


            })(appItemEnumerator.get_current());
        };

    }, function (sender, args) {
        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    });
};

jsAppwebPart._xmlInputElement = null;
jsAppwebPart._xslInputElement = null;

jsAppwebPart._ensureXmlSection = function (sourceWebPartId) {

    var xmlSourceTitle = jsAppwebPart._headers.get(0);
    var xmlSourceBody = jsAppwebPart._bodies.get(0);

    var xmlLinkTitle = jsAppwebPart._headers.get(1);
    var xmlLinkBody = jsAppwebPart._bodies.get(1);

    var xmlEditorLink = $("#MsoXmlToolpartBasicAddXml").get(0);
    var xmlTestLink = $("#MsoXmlToolpartBasicTestLink_xml").get(0);

    var xmlInput = $("input", xmlLinkBody).get(0);

    jsAppwebPart._xmlInputElement = xmlInput;

    jQuery(xmlSourceTitle).html("Application");
    jQuery(xmlSourceBody).hide();



    //jQuery(xmlSourceTitle).hide();
    //jQuery(xmlSourceBody).hide();

    jQuery(xmlLinkTitle).hide();
    jQuery(xmlLinkBody).hide();


    jQuery(xmlEditorLink).val("Select app...");
    jQuery(xmlTestLink).hide();

    var newAppButton = $("<div class='UserSectionBody'>To change app, click <b>Select app</b>.<br /><div class='UserControlGroup' style='padding-top:5px;'><input type='button' class='UserButton' value='Select app...' /> </div></div>");

    jQuery(xmlLinkTitle).after(newAppButton);

    jQuery(newAppButton)
                 .attr('onclick', '')
                 .unbind('click')
                 .click(function () {
                     jsAppwebPart._showAppPicker();
                 });

    jQuery(xmlLinkTitle).after(newAppButton);

};

jsAppwebPart._ensureXslSection = function (sourceWebPartId) {

    var xslSourceTitle = jsAppwebPart._headers.get(2);
    var xslSourceBody = jsAppwebPart._bodies.get(2);

    var xslLinkTitle = jsAppwebPart._headers.get(3);
    var xslLinkBody = jsAppwebPart._bodies.get(3);

    var xslTestLink = $("#MsoXmlToolpartBasicTestLink_xsl").get(0);
    var xslInput = $("input", xslLinkBody).get(0);

    jsAppwebPart._xslInputElement = xslInput;


    jQuery(xslSourceTitle).hide();
    jQuery(xslSourceBody).hide();

    jQuery(xslLinkTitle).hide();
    jQuery(xslLinkBody).hide();

    jQuery(xslTestLink).hide();
};

if (typeof jQuery == 'undefined') {
    console.log("JsAppWebpart :: JsAppWebpart require jQuery. Please make sure jQuery is loaded");
} else {

    console.log("JsAppWebpart :: jQuery is loaded!");

    var webpartAreas = jQuery("td[id^='MSOZoneCell_']");

    jQuery(webpartAreas).each(function (index, item) {

        console.log("JsAppWebpart :: wp:" + this.id);

    });

}